import os
from os import PathLike
from collections import OrderedDict
import pandas as pd

class Returns(object):
    """ 构造Server Return返回值

        Args:
            project (str): 项目名称
            csv_def (PathLike): 输入csv文件路径
    """
    def __init__(self, project:str, csv_def:PathLike=None):
        
        self.prefix = project.upper()
        self.codes = OrderedDict()
        if csv_def and os.path.exists(csv_def) and csv_def.endswith('.csv'):
            df = pd.read_csv(csv_def)
            for i in range(df.shape[0]):
                values = df.loc[i]
                self.codes[str(values['code'])] = values['msg'] if values['msg'].startswith(self.prefix) else self.prefix + ':' + values['msg'] 
        else:
            self.codes['0'] = self.prefix + ':execution succeed'

    def succeed(self):
        return 0

    def bind(self, code:int, msg:str):
        """注册绑定错误代码和提示信息

        Args:
            code (int): 错误代码
            msg (str): 提示信息
        """
        if str(code) in self.codes.keys():
            raise KeyError(self.prefix + ':[%s] the key is already registered.' % (str(code)))
        else:
            self.codes[str(code)] = self.prefix + ':' + msg

    def __get_msg(self, code):
        return self.codes[str(code)]

    def doc(self, path='./'):
        """生成帮助文件

        Args:
            path (str, optional): 帮助文件生成路径. Defaults to './'.
        """
        if not os.path.exists(path):
            os.makedirs(path)
        with open(os.path.join(path, self.prefix + '.help.csv'), 'w') as f:
            f.write('code,msg\n')
            codes = sorted(self.codes.items(), key=lambda x: int(x[0]))
            for code, msg in codes:
                f.write('%s,%s\n' % (str(code), msg))
    
    def __setitem__(self, code:int, msg:str):
        self.bind(code, msg)
    
    def warp(self, code:int, ret:any):
        """生成返回代码

        Args:
            keys (tuple): (需要返回的值any, 确定返回代码int)

        Raises:
            ValueError: 返回代码不在列表中

        Returns:
            dict: 返回结构体
        """
        if str(code) not in self.codes.keys():
            raise KeyError(self.prefix + ": make sure your code in Returns")

        fret = {
            "code": code,
            "res": ret,
            "msg": self.__get_msg(code)
        }

        return fret


if __name__ == "__main__":
    app = Returns('demo', 'DEMO.help.csv')

    #app.bind(404, "can not find the key")
    #app.bind(500, 'gaia failed key')

    #app.doc('demo')
    app[10] = 'can not find the key'

    app.doc('demo')
    print(app.warp(0, {"a": 20}))

